package com.lsj.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lsj.mapper.entity.MyUserDetail;
import com.lsj.mapper.entity.SysOrg;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/*
1.strictInsertFill和strictUpdateFill最后都是调用同一个方法
2.根据官网的说法，都是在有值的情况下不会填充
3.因此在更新时就不能使用strictUpdateFill，使用setFieldValByName可以实现在更新时填充
* */
@Component
public class MybastisColumnsHandler implements MetaObjectHandler {

    private static final Integer version = 1000000000;

    @Override
    public void insertFill(MetaObject metaObject) {
        MyUserDetail user = getUser();
        this.strictInsertFill(metaObject, "createBy", String.class, user.getUsername());
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
        this.strictInsertFill(metaObject, "version",Integer.class, version);
        this.strictInsertFill(metaObject, "updateBy", String.class, user.getUsername());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        MyUserDetail user = getUser();
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateBy", user.getUsername(), metaObject);
    }

    private MyUserDetail getUser(){
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        MyUserDetail user = null;
        if(principal != null && principal instanceof MyUserDetail){
            user = (MyUserDetail)principal;
        }else{
            user = getAnonymousUser();
        }
        return user;
    }

    /**
     * @Author: lin.sj
     * @Date: 2021/8/9 20:01
     * @Desc: 获取匿名用户信息(在获取不到登录用户的情况下使用),此处最多只用到个人信息及机构信息，权限信息不需要，因此无需构造
     **/
    private MyUserDetail getAnonymousUser(){
        //生成人员基本信息
        MyUserDetail user = new MyUserDetail();
        user.setUsername("sys");
        user.setName("后台自动生成");
        //生成根节点信息
        SysOrg sysOrg = new SysOrg();
        sysOrg
                .setId(0L)
                .setOrgName("根组织")
                .setOrgPid(-1L)
                .setOrgPids("[-1]")
                .setOrgCode("00");
        user.setSysOrg(sysOrg);
        return user;
    }

}